package com.rycx.facefeatureclient.util;


import okhttp3.*;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

public class OKHttpUtil {

    public static final OkHttpClient okHttpClient = new OkHttpClient().newBuilder().connectTimeout(5 * 60 * 60 * 1000, TimeUnit.MILLISECONDS)
            .readTimeout(5 * 60 * 60 * 1000, TimeUnit.MILLISECONDS).writeTimeout(5 * 60 * 60 * 1000, TimeUnit.MILLISECONDS).build();


    public static String postJsonParams(String url, String jsonParams) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request.Builder build = new Request.Builder().url(url).post(requestBody);
        Request request = build.build();
        return doRequest(request,url);
    }

    private static String doRequest(Request request, String url){
        String responseBody;
        Response response = null;
        OkHttpClient myclient = null;
        long startTime = System.currentTimeMillis();
        try {
            if(url.startsWith("https")){
                myclient = new OkHttpClient.Builder().connectTimeout(300, TimeUnit.SECONDS)
                        .readTimeout(300, TimeUnit.SECONDS).writeTimeout(300, TimeUnit.SECONDS)
                        .build();
            }else{
                myclient = new OkHttpClient().newBuilder().connectTimeout(300, TimeUnit.SECONDS)
                        .readTimeout(300, TimeUnit.SECONDS)
                        .writeTimeout(300, TimeUnit.SECONDS)
                        .build();
            }
            response = myclient.newCall(request).execute();
            if (response.body() != null) {
                responseBody = response.body().string();
                return responseBody;
            } else {
                return null;
            }
        } catch (SocketTimeoutException e) {
            responseBody = "{'code':1,'msg':'service time out" + url + "'}";
        } catch (Exception e) {
            responseBody = "{'code':1,'msg':'service request exception" + url + "'}";
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }
}
